let win = null;


const getBounds = (x,y) => {
  let displayMatching = utools.getDisplayNearestPoint({x,y});
  let display = utools.getPrimaryDisplay();
  let displayMatchingScaleFactor =  displayMatching.scaleFactor;
  let displayScaleFactor =  display.scaleFactor;

  let difference = displayScaleFactor - displayMatchingScaleFactor;
  return function (width, height){
    let x = displayMatching.bounds.x + parseInt(displayMatching.bounds.width / 2 - width / 2);
    let y = displayMatching.bounds.y + parseInt(displayMatching.bounds.height / 2 - height / 2);
    if(difference > 0){
      width = parseInt(width * (1 + difference));
      height = parseInt(height * (1 + difference));
      return {
        x, y, width, height
      }
    }else if(difference < 0){
      width = parseInt(width / (1 - difference));
      height = parseInt(height / (1 - difference));
      return {
        x, y, width, height
      }
    }else{
      return {
        x,
        y,
        width,
        height
      }
    }
  }
}

window.openPopup = (url, options) => {
  if(win)return;
  let data = options?.data
  let { width, height, x, y } = getBounds(options.x, options.y)(options.width, options.height);

  return new Promise((resolve, reject) => {

    let ubWindow = utools.createBrowserWindow(url, {
      title: 'popup',
      skipTaskbar: true,
      frame: false,
      backgroundColor: "rgba(255,255,255,0)",
      transparent: true,
      titleBarStyle: "hidden",
      // resizable: false,
      width,
      height,
      x,
      y,
      webPreferences: {
        preload: "./haoyongnotesPendant/preload.js",
        spellcheck: false,
      },
    }, ()=>{
      ubWindow.show();
      ubWindow.setBackgroundColor("rgba(255,255,255,0)");
      // ubWindow.webContents.openDevTools();
      
      ipcRenderer.sendTo(ubWindow.webContents.id, "senderId");
      ipcRenderer.sendTo(ubWindow.webContents.id, "init", data);
      ubWindow.setAlwaysOnTop(true, 'pop-up-menu');
      win = ubWindow;
      resolve(ubWindow);
    });
  })

}


ipcRenderer.on("win", (event, type) => {
  switch (type) {
    case "close":
      win.destroy();
      win = null;
      break;
    // case "setEmojin":
      
    default:
      break;
  }
});


// window.closePopupWin = () => {
//   win.destroy();
//   win = null;
// }